import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-04-15
 * Time: 16:50
 */
public class TestCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个有返回值的任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        // 使用 FutureTask 包装一下。相当于是一张对应于上面任务的小票
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        // 创建线程, 线程的构造方法传入 FutureTask . 此时新线程就会执行 FutureTask 内部的 Callable 的
        // call 方法, 完成计算. 计算结果就放到了 FutureTask 对象中
        Thread t = new Thread(futureTask);

        t.start();
        // 在主线程中调用 futureTask.get() 能够阻塞等待新线程计算完毕.无需使用 join
        int sum = futureTask.get();

        System.out.println(sum);
    }
//    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        Callable<Integer> callable = new Callable<Integer>() {
//            @Override
//            public Integer call() throws Exception {
//                int sum = 0;
//                for (int i = 0; i <= 100; i++) {
//                    sum += i;
//                }
//                return sum;
//            }
//        };
//        FutureTask<Integer> futureTask = new FutureTask<>(callable);
//        Thread t = new Thread(futureTask);
//        t.start();
//        System.out.println(futureTask.get());
//
//    }
}
